package com.xin.uploadanddownload.test;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.stream.IntStream;

public class CheckPDF {
    /**
     * 校验pdf文件是否包含js脚本
     **/
    public static boolean containsJavaScript(File file) throws IOException {
        PDDocument document = PDDocument.load(file);
        return containsJavaScript(document);
    }

    /**
     * 校验pdf文件是否包含js脚本
     **/
    public static boolean containsJavaScript(InputStream input) throws IOException {
        PDDocument document = PDDocument.load(input);
        return containsJavaScript(document);
    }

    /**
     * 校验pdf文件是否包含js脚本
     **/
    public static boolean containsJavaScript(PDDocument document) {
        //Getting the PDDocumentInformation object
        PDPageTree pages = document.getPages();
        return IntStream.range(0, pages.getCount()).anyMatch(i -> {
            //return str.contains("JavaScript") || str.contains("COSName{JS}");
            return pages.get(i).getCOSObject().toString().contains("COSName{JS}");
        });
    }

    public static void main(String args[]) throws IOException {
        //Loading an existing document
        String s1 = "xss2.pdf";
        File file = new File("D:\\" + s1);
        boolean b = containsJavaScript(file);
        if (b) {
            System.out.println("pdf文件包含，js脚本代码");
        }
    }
}
